<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               v-model:search="search"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               >
      <!--<template #menu-left>-->
        <!--&lt;!&ndash;<span style="color:dimgrey; padding-left: 5px; display:flex; transform: translateY(100%); width: 80%;">12321321{{workListTips}}</span>&ndash;&gt;-->
        <!--<el-row style="width: 100%;" :gutter="20">-->
          <!--<el-col :span="16" v-if="workListTips">-->
            <!--<el-tooltip class="item" effect="dark" :content="workListTips" placement="top">-->
              <!--<div class="ellipsis">-->
                <!--选择的工序：{{workListTips}}-->
              <!--</div>-->
            <!--</el-tooltip>-->
          <!--</el-col>-->
        <!--</el-row>-->
      <!--</template>-->

      <template #menu-left>
        <el-form-item>
          <el-row style="width: 60%;" :gutter="20">
            <el-col :span="24" v-if="workListTips">
              <el-tooltip class="item" effect="dark" :content="workListTips" placement="top">
                <div class="ellipsis">
                  选择的工序：{{workListTips}}
                </div>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form-item>
        <el-button
                type="warning"
                icon="el-icon-download"
                v-if="permission.bom_calc_export"
                @click="handleExport"
        >导出
        </el-button>
      </template>

      <template #num-search="{ disabled, size }">

      <avue-input-number :controls="false" :min="1" v-model="search.num"  placeholder="请输入数量" style="width: 100%"></avue-input-number>
      </template>
    </avue-crud>
    <el-dialog title="请选择工序" append-to-body v-model="box" width="60%">
      <el-tree
              :default-expand-all="true"
              :check-strictly="true"
              :data="workListData"
              show-checkbox
              node-key="id"
              ref="treeMenu"
              :props="props"
              @check-change="menuCheck"
              :render-content="renderContent"
      >
      </el-tree>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="this.box = false">取 消</el-button>
          <el-button type="primary" @click="calcMaterial">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--<template #search="{ disabled, size }">-->
      <!--<el-form-item-->
              <!--label="物料编号"-->
              <!--prop="nodeNo"-->
              <!--:rules="[{ required: true, message:'物料编号不能为空' }]"-->
      <!--&gt;-->
      <!--<el-input v-model="query.nodeNo"  placeholder="请输入物料编号"></el-input>-->
      <!--</el-form-item>-->
    <!--</template>-->
  </basic-container>
</template>

<script>
  import {checkByCalc, workListSelect,calcBom} from "@/api/anwise/material/bom_list";
  import {mapGetters} from "vuex";
  import { getToken } from '@/utils/auth';
  import { exportBlob ,exportBlobPost} from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
    data() {
      return {
          box:false,
          props: {
              label: 'nodeName',
              value: 'id',
          },
          workListTips:'',
          workList:[],
          workListData:[],
          form: {},
          query: {},
          loading: false,
          dateFormat: 'YYYY-MM-DD',
          pickerOptions: {},
          page: {
              pageSize: 20,
              currentPage: 1,
              total: 0
          },
          search:{},
        searchForm:{},
          selectionList: [],
          option: {
              height:'auto',
              calcHeight: 30,
              tip: false,
              searchShow: true,
              refreshBtn:false,
              searchShowBtn:false,
              emptyBtn:false,
              columnBtn:false,
              searchMenuSpan: 6,
              border: true,
              index: true,
              selection: false,
              labelWidth: 150,
              indexWidth:100,
              menuWidth: 160,
              menu:false,
              addBtn: false,
              editBtn: false,
              viewBtn: false,
              delBtn: false,
              stripe: true,
              searchIndex: 3,
              searchIcon: false,
              searchBtnText:'计算',
            searchEnter:true,
          column: [

              {
                  label: "物料编号",
                  prop: "nodeNo",
                  type: "input",
                  fixed: true,
                  search: true,
                  overHidden: true,
                  width:200,
              },
              {
                  label: "物料名称",
                  prop: "nodeName",
                  type: "input",
                  fixed: true,
                  overHidden: true,
                  width:200,
              },
              {
                  label: "类别",
                  prop: "type",
                  type: "input",
                  overHidden: true,
                  width:160,
              },
              {
                  label: "数量",
                  prop: "num",
                  type: "input",
                  search:true,
                  overHidden: true,
                  width:200,
              },

              {
                  label: "单位",
                  prop: "unit",
                  type: "input",
                  overHidden: true,
                  width:200,
              },
          ]
        },
        data: [],
        ifullscreen:false
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.order_add, false),
          viewBtn: this.validData(this.permission.order_view, false),
          delBtn: this.validData(this.permission.order_delete, false),
          editBtn: this.validData(this.permission.order_edit, false),
          exportBtn: this.validData(this.permission.bom_calc_export, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleFullScreen() {
        this.ifullscreen = !this.ifullscreen;
      },
      handleExport() {
        if(!this.data || this.data.length === 0){
          this.$message.error('请先输入物料与数量进行计算！');
          return;
        }
        NProgress.start();
        exportBlobPost(
                `/blade-anwise/material/bom_list/exportCalcBom?${this.website.tokenHeader
                }=${getToken()}`, this.searchForm
        ).then(res => {
          downloadXls(res.data, `【`+this.searchForm.nodeNo+`】Bom数据${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
          NProgress.done();
        });
      },
        renderContent(h, {data}){
            return h(
                'span',
                {
                    style: {
                        color: '#626AEF',
                    },
                },
                data.nodeName+" [<"+data.parentNo+">"+data.parentName+"]-("+(data.modelNo || '无工模')+")"
            )
        },
            menuCheck(data, isChecked) {
            console.log(this.$refs.treeMenu.getNode(data.id))
            if (isChecked) {
                if (data.parentId) {
                    this.setParentCheck(data.id)
                }
            } else {
                this.setChildUncheck(data.id)
            }
        },
        setChildUncheck(id) {
            const node = this.$refs.treeMenu.getNode(id);
            if (node.data.children) {
                node.data.children.forEach(item => {
                    this.$refs.treeMenu.setChecked(item.id, false);
                    this.setChildUncheck(item.id)
                })
            }
        },
        setParentCheck(id) {
            const node = this.$refs.treeMenu.getNode(id);
            if (node.data.parentId) {
                this.$refs.treeMenu.setChecked(node.data.parentId, true);
                this.setParentCheck(node.data.parentId)
            }
          // this.workList.forEach(item => {
          //     if (id === item.id && item.parentId) {
          //         this.$refs.treeMenu.setChecked(item.parentId, true);
          //         this.setParentCheck(item.parentId);
          //     }
          // })
        },
        calcMaterial() {
            this.loading = true;
            console.log(this.$refs.treeMenu.getCheckedNodes(false, true));
            const workListCheck = this.$refs.treeMenu.getCheckedNodes(false, true);
            this.workListTips = "";
            workListCheck.forEach(item => {
               this.workListTips += item.level+":"+item.nodeName+"-"+item.parentNo+"/";
            });
            console.log(this.workListTips);
            if (this.workListTips.length > 0) {
                this.workListTips = this.workListTips.substring(0, this.workListTips.length-1);
            }
            const form = {
             nodeNo: this.query.nodeNo,
             num: this.query.num,
             workList:this.$refs.treeMenu.getCheckedNodes(false, true)
            }
            this.searchForm = form;
            calcBom(form).then(res =>{
                if (res.data.success) {
                    this.data = res.data.data;
                    this.box = false;
                    this.loading = false;
                }
            }).catch(() => {
                this.loading = false;
            });
        },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchChange(params, done) {
          if (!params.nodeNo || !params.num) {
              this.$message.error('请输入物料编号和数量！');
              done();
              return;
          }
          // checkByCalc(params.nodeNo).then(res => {
          //     if (res.data.success) {
                  workListSelect(params.nodeNo).then(res =>{
                      if (res.data.success) {
                          this.workListData = res.data.data.workTree;
                          this.workList = res.data.data.workList;
                        this.ifullscreen = false;
                          this.box = true;
                      }
                  })
          //     } else {
          //         this.$message.error(res.data.msg || "当前物料Bom结构异常！");
          //     }
          // })
          setTimeout(() =>{
              this.$nextTick(() => {
                  console.log("this.$refs.treeMenu", this.$refs.treeMenu);
                  this.$refs.treeMenu.setCheckedNodes(this.workList);
              });
          },500)
        this.query = params;
        this.page.currentPage = 1
        // this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {

      }
    }
  };
</script>

<style scoped>
  .row-yellow {
    background-color: rgb(255, 253, 230) !important;
    cursor: pointer;
  }
  .ellipsis {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
